# models/user.py
"""
Author: didiplus
Description: 用户模型定义
Date: 2025-08-20 20:37:07
LastEditors: didiplus
LastEditTime: 2025-08-20 20:37:08
FilePath: /WeChatBot/app/models/user.py
Version: 1.0
"""
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, func
from sqlalchemy.orm import relationship
import hashlib

from .base import BaseModel

class User(BaseModel):
    """
    用户模型
    用于存储用户基本信息和认证信息
    """
    __tablename__ = "users"
    
    #: 用户名，唯一且不能为空
    username = Column(String(50), unique=True, index=True, nullable=False, comment="用户名")
    
    #: 邮箱地址，唯一
    email = Column(String(100), unique=True, index=True, nullable=True, comment="邮箱地址")
    
    #: 密码哈希值，不能为空
    password_hash = Column(String(255), nullable=False, comment="密码哈希值")
    
    #: 用户昵称
    nickname = Column(String(100), nullable=True, comment="用户昵称")
    
    #: 是否为超级用户
    is_superuser = Column(Boolean, default=False, nullable=False, comment="是否为超级用户")
    
    # 关联关系
    keyword_rules = relationship("KeywordRuleModel", back_populates="user", cascade="all, delete-orphan")
    
    def _hash_password(self, password: str) -> str:
        """
        简单的密码哈希处理
        
        Args:
            password (str): 明文密码
            
        Returns:
            str: 哈希后的密码
        """
        # 使用SHA256进行简单哈希（仅用于演示，实际项目中请使用bcrypt）
        return hashlib.sha256(password.encode('utf-8')).hexdigest()
    
    def verify_password(self, password: str) -> bool:
        """
        验证密码
        
        Args:
            password (str): 待验证的密码明文
            
        Returns:
            bool: 密码是否正确
        """
        # 比较哈希值
        return self.password_hash == self._hash_password(password)
    
    def set_password(self, password: str):
        """
        设置密码哈希值
        
        Args:
            password (str): 密码明文
        """
        self.password_hash = self._hash_password(password)
    
    def is_admin(self) -> bool:
        """
        检查用户是否为管理员
        
        Returns:
            bool: 是否为管理员
        """
        return self.is_superuser
    
    def to_dict(self, include_sensitive: bool = False) -> dict:
        """
        将用户对象转换为字典
        
        Args:
            include_sensitive (bool): 是否包含敏感信息
            
        Returns:
            dict: 用户信息字典
        """
        data = {
            "id": self.id,
            "username": self.username,
            "email": self.email,
            "nickname": self.nickname,
            "is_active": self.is_active,
            "is_superuser": self.is_superuser,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }
        
        if include_sensitive:
            data["password_hash"] = self.password_hash
            
        return data